package com.poh.controller;

import com.poh.pojo.AnswerQuestion;
import com.poh.pojo.ChoiceQuestion;
import com.poh.pojo.Course;
import com.poh.service.AnswerQuestionService;
import com.poh.service.ChoiceQuestionService;
import com.poh.service.QuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class AnswerQuestionController {
    @Autowired
    AnswerQuestionService answerQuestionService;
    @Autowired
    QuestionBankService questionBankService;
    @Autowired
    ChoiceQuestionService choiceQuestionService;
    @PostMapping("/addAnswerQuestion")
    public String addAnswerQuestion(AnswerQuestion answerQuestion, HttpSession session) {
        String questionBankId = (String) session.getAttribute("questionBankId");
        System.out.println(questionBankId);
        answerQuestion.setQuestionBankId(questionBankId);
        answerQuestionService.addAnswerQuestion(answerQuestion);
        return "redirect:/toAddQuestionBank";
    }

    @GetMapping("/deleteAnswerQuestion/{answerQuestionId}")
    public String deleteAddAnswerQuestion(@PathVariable("answerQuestionId") int answerQuestionId) {
        answerQuestionService.deleteAnswerQuestionById(answerQuestionId);
        return "redirect:/toAddQuestionBank";
    }

    @GetMapping("deleteAnswerQuestion/{answerQuestionId}/{questionBankId}")
    public String deleteAnswerQuestion(@PathVariable("answerQuestionId") int answerQuestionId,
                                       @PathVariable("questionBankId") String questionBankId,
                                       HttpSession session) {
        Course course = (Course) session.getAttribute("course");
        answerQuestionService.deleteAnswerQuestionById(answerQuestionId);
        if (choiceQuestionService.getChoiceQuestionByQuestionBankId(questionBankId).isEmpty() && answerQuestionService.queryAnswerQuestionByQuestionBankId(questionBankId).isEmpty()) {
            questionBankService.deleteQuestionBank(questionBankId);
            return "redirect:/getHomework/" + course.getCourseId();
        }
        return "redirect:/intoHomework/" + questionBankId;
    }

    @PostMapping("/updateInfoAnswerQuestion")
    public String updateInfoAnswerQuestion(AnswerQuestion answerQuestion) {
        answerQuestionService.updateAnswerQuestion(answerQuestion);
        return "redirect:/intoHomework/" + answerQuestion.getQuestionBankId();
    }

    @PostMapping("/updateAnswerQuestion")
    public String updateAnswerQuestion(AnswerQuestion answerQuestion) {
        answerQuestionService.updateAnswerQuestion(answerQuestion);
        return "redirect:/toAddQuestionBank";
    }
}
